#include <stdlib.h>
#include <stdio.h>
#include <getopt.h>
#include <string.h>

#include "netopt.h"

static struct option long_options[] = {
	{"addr",       1, 0, 'd' },
	{"host",       1, 0, 'h' },
	{"user",       1, 0, 'u' },
	{"pass",       1, 0, 's' },
	{"log",        1, 0, 'g' },
	{"port",       1, 0, 'p' },
	{"verbose",    0, 0, 'v' },
	{"laddr",      1, 0, 'l' },
	{"lport",      1, 0, 'b' },
	{"help",       0, 0, 'e' },
	{"path",       1, 0, 't' },
	{"file",       1, 0, 'f' },
	{"url",        1, 0, 'r' },
	{"count",      1, 0, 'c' },
	{"timing",     0, 0, 'i' },
	{0,            0, 0,  0  }
};
struct netopt o = {
-1,
0,0,0,0,0,
0,0,0,0,0,
0,0,0,0,0};

void usage(const char* av0){
	printf("Usage: %s",av0);
	int i = 0;
	for(;;){
		printf(" --%s|%c",long_options[i].name,long_options[i].val);
		if(long_options[i].has_arg){
			printf(" <%s>",long_options[i].name);
		}
		i++;
		if(!long_options[i].name){
			break;
		}
	}
	printf("\n");
}

struct netopt* netopt(int argc, char **argv) {
	int c;
	int digit_optind = 0;

	while (1) {
		int this_option_optind = optind ? optind : 1;
		int option_index = 0;

		c = getopt_long(argc, argv, "", long_options, &option_index);
		if (c == -1)
			break;
		switch (c) {

		case 'd':
			strcpy(o.addr,optarg);
			break;
		case 'h':
			strcpy(o.host,optarg);
			break;
		case 'u':
			strcpy(o.user,optarg);
			break;
		case 's':
			strcpy(o.pass,optarg);
			break;
		case 'g':
			strcpy(o.log,optarg);
			break;
		case 'p':
			o.port = atoi(optarg);
			break;
		case 'c':
			o.count = atoi(optarg);
			break;
		case 'v':
			o.verbose++;
			break;
		case 'i':
			o.timing++;
			break;
		case 'b':
			o.lport = atoi(optarg);
			break;
		case 'l':
			strcpy(o.laddr,optarg);
			break;
		case 't':
			strcpy(o.path,optarg);
			break;
		case 'f':
			strcpy(o.file,optarg);
			break;
		case 'r':
			strcpy(o.url,optarg);
			break;
		case 'e':
			usage(argv[0]);
			return 0;
		case '?':
			return 0;
		}
	}

	if (optind < argc) {
		o.last = optind;
	}
	return &o;
}
